package cn.ljy.authority.exception.handle;


import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.model.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author ljy
 * 20210121创建
 * 20210121最后修改
 * 用于处理本module的spring security的所有异常信息并返回前端
 * 说明：使用此异常类，应按照把业务层异常往控制层抛，并且在控制层不轻易做异常处理，都交由此类处理
 */
@Slf4j
@ControllerAdvice
@ResponseBody
@Order(99)
public class MySecurityExceptionHandler {
    /**
     * spring security的拒绝访问异常
     * @param e
     * @return
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseData accessDeniedException(AccessDeniedException e) {
        //ResponseData responseData=new ResponseData(ResultCode.FORBIDDEN.getCode(),e.getMessage());
        log.info("spring security拒绝访问异常：{}", e.getMessage());
        return ResponseData.error(ResultCode.FORBIDDEN.getCode(),ResultCode.FORBIDDEN.getMsg());
    }

    /**
     * 从spring security找不到上下文时会出现的异常，即没有token的异常，由spring security自带拦截器拦截
     * @author ljy
     * 20220129
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler
    public ResponseData authenticationCredentialsNotFoundException(AuthenticationCredentialsNotFoundException e) {
        //ResponseData responseData=new ResponseData(ResultCode.FORBIDDEN.getCode(),e.getMessage());
        log.info("spring security中没有保存的登录信息：{}", e.getMessage());//An Authentication object was not found in the SecurityContext",
        return ResponseData.error(ResultCode.UNAUTHORIZED.getCode(),"请先登录");
    }


    /**
     * spring security的登录等异常（如账户名不存在、账户过期）
     * @param e
     * @return
     */
  /*  @ExceptionHandler({ DisabledException.class })
    public ResponseData  authenticationException(DisabledException e) {
        ResponseData responseData=new ResponseData(ResultCode.FORBIDDEN.getCode(),e.getMessage());
        log.info("spring security登录异常（如账户名不存在、账户过期）", e.getMessage());
        return responseData;
    }*/

}
